import { defineComponent, reactive, watch, inject } from "vue"
import useMemo from "../_util/hooks/useMemo"
import { checkboxGroupContext } from "./Group"

export default defineComponent({
  name: 'x-checkbox',
  props: {
    prefixCls: { default: 'x-checkbox' },
    checked: Boolean,
    disabled: Boolean,
    name: String,
    value: [String, Number],
    type: { default: 'checkbox' }
  },
  emits: ['update:checked', 'change'],
  setup(props, { emit, slots }) {
    const groupContext = inject(checkboxGroupContext)
    const disabledRef = useMemo(() => groupContext?.disabledRef?.value || props.disabled)
    const nameRef = useMemo(() => groupContext?.nameRef?.value || props.name)

    const state = reactive({
      checked: props.checked,
      focused: false
    })
    watch(() => props.checked, checked => {
      state.checked = checked
    })
    const checkedRef = useMemo(() => {
      if (groupContext) return groupContext.valueRef.value.includes(props.value)
      return state.checked
    })


    function onChange(e: Event) {
      if (props.disabled) return
      // @ts-ignore
      const val = e.target.checked
      if (groupContext) {
        groupContext.toggleOption({label: slots.default?.(), value: props.value})
      } else {
        state.checked = val
        emit('update:checked', val)
      }
      emit('change', val)
    }

    function onFocus() {
      state.focused = true
    }
    function onBlur() {
      state.focused = false
    }
    
    return () => {
      const { prefixCls } = props
      const radioProps = {
        class: [prefixCls, {
          [`${prefixCls}-checked`]: checkedRef.value,
          [`${prefixCls}-focused`]: state.focused,
          [`${prefixCls}-disabled`]: disabledRef.value,
        }],
      }

      const inputProps = {
        class: `${prefixCls}_input`,
        name: nameRef.value,
        value: props.value,
        type: props.type,
        checked: !!checkedRef.value,
        disabled: disabledRef.value,
        onFocus,
        onBlur,
        onChange
      }

      return (
        <label {...radioProps}>
          <input {...inputProps} />
          <div class={`${prefixCls}_dot`}></div>
          <div class={`${prefixCls}_label`}>{slots.default?.()}</div>
        </label>
      )
    }
  }
})